package com.suman.bbcticker.configure;


import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.location.LocationListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.suman.bbcticker.ApplicationStateObjectsHolder;
import com.suman.bbcticker.Eula;
import com.suman.bbcticker.R;
import com.suman.bbcticker.activity.WrongLaunchAlertActivity;
import com.suman.bbcticker.service.RssReaderService;
import com.suman.bbcticker.utils.CleanUpUtils;
import com.suman.bbcticker.weather.GoogleWeatherService;
import com.suman.bbcticker.widget.SkyNewsReaderAppWidget;

public class PreferenceLauncherActivity extends Activity {
	private static final String TAG = "PreferenceLauncherActivity";
	public static final String PREFS_NAME = "com.suman.rss.configure.PreferenceLauncherActivity";
	public static final String TICKER_ALERTTYPE_SOUND_KEY = "ticker_alerttype_sound_key";
	public static final String TICKER_ALERTTYPE_VIBRATE_KEY = "ticker_alerttype_vibrate_key";
	public static final String TICKER_ALERTTYPE_NOTIFICATION_KEY = "ticker_alerttype_notification_key";
	public static final String TICKER_ALERTTYPE_SITESELECTED_KEY = "ticker_selectedsite_key";
	public static final String TICKER_ALERTTYPE_FEEDREFRESHTIME_KEY = "ticker_feedrefreshtime_key";
	public static final String TICKER_ALERTTYPE_KEYWORD_KEY = "ticker_alerttype_keyword_key";
	
	public static final String TICKER_ALERTTYPE_SITESELECTED_CUSTOMURL_CHECKBOXKEY = "ticker_selectedsite_customurl_checkbox_key";	
	public static final String TICKER_ALERTTYPE_SITESELECTED_CUSTOMURL_EDITTEXTKEY = "ticker_selectedsite_customurl_edittext_key";
	
	public static final String TICKER_WEATHERSELECTION_GPS_CHECKBOXKEY = "ticker_weatherselection_gpscheckbox_key";
	public static final String TICKER_WEATHERSELECTION_CUSTOMLOCATION_CHECKBOXKEY = "ticker_weatherselection_customlocationcheckbox_key";	
	public static final String TICKER_WEATHERSELECTION_CUSTOMLOCATION_EDITTEXTKEY = "ticker_weatherselection_customlocationedittext_key";
	
	
	public static final String PREF_PREFIX_KEY = "prefix_";
	private int mAppWidgetId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		updateDisplayStringToSiteUrlMap();
		// get any data we were launched with
		/*
		 * 1)Config button for preferences 2)sp and dip measurement for layout
		 * stuff 3)keyword based alert
		 */
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras == null) {
			Intent cancelResultValue = new Intent();
			cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_CANCELED, cancelResultValue);

			Intent intent = new Intent();
			intent.setClass(this, WrongLaunchAlertActivity.class);
			startActivity(intent);

			finish();
		} else {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

			Intent cancelResultValue = new Intent();
			cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_CANCELED, cancelResultValue);
			if (Intent.ACTION_MAIN.equalsIgnoreCase(launchIntent.getAction()) && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)) {

				Intent intent = new Intent();
				intent.setClass(this, WrongLaunchAlertActivity.class);
				startActivity(intent);

				finish();
			} else {

				Intent launchPreferencesIntent = new Intent().setClass(this, FeedTickerPreferences.class);
				launchPreferencesIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
				startActivityForResult(launchPreferencesIntent, mAppWidgetId);
			}
		}

	}

	/**
	 * This method updates hashmap for easy access of siteselection URL from what users have selected in front end.
	 */
	private void updateDisplayStringToSiteUrlMap() {		
		Resources res = getResources(); 
		String[] siteSelectionEntryListArray = res.getStringArray(R.array.ticker_siteselectionpreferences_entries_list);
		String[] siteSelectionEntryValueArray = res.getStringArray(R.array.ticker_siteselectionpreferences_entries_values);
		for(int i=0;i<siteSelectionEntryListArray.length;i++){
			ApplicationStateObjectsHolder.displayStringToSiteUrlMap.put(siteSelectionEntryListArray[i],siteSelectionEntryValueArray[i]);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		final SharedPreferences preferences = getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE);
		if (!preferences.getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) {
			finish();

		} else {
			if (requestCode == mAppWidgetId) {
				// TODO put default values for each preferences in xml
				// And update description to talk abt default values..again in
				// xml
				// And raise a toast saying preferences have been saved
				Toast.makeText(this, "Your Preferences have been Saved", Toast.LENGTH_SHORT).show();

				updatePreferenceMapWithUserPreferences(mAppWidgetId);
				try {
					configureGoogleWeatherService(mAppWidgetId);
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				configureAlarm();
				setResultForActivity();
				savePreferenceAsString(this, PREF_PREFIX_KEY + mAppWidgetId, "saved");
				updateRemoteViewWithLoadingMessage(this, mAppWidgetId);
			}

		}

	}

	private void configureGoogleWeatherService(int appWidgetId) throws Throwable {
		//Using this map..Wrong one to use..i know...but what to do..
		//iam going mad...this code is getting out of hands now...may be i should delete everything and run away
		//or may be not:)
		if(ApplicationStateObjectsHolder.locationListenerMap.containsKey(appWidgetId)){
			//This case means that its the case when user have pressed config button and they wanna reconfigure it
			//removing the ecisting config and reinvoking again
			new CleanUpUtils().cleanupLocationListenerForWeatherService(this, appWidgetId);	
		}
		/** start weather service..*/
		LocationListener locationListenerForWeather = new GoogleWeatherService().handleWeather(this,appWidgetId);
		ApplicationStateObjectsHolder.locationListenerMap.put(appWidgetId, locationListenerForWeather);
	}

	/**
	 * Save the preference values in HashMap...
	 * 
	 * @param appWidgetId
	 */

	private void updatePreferenceMapWithUserPreferences(int appWidgetId) {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		resetCurrentFeedForWidgetInstance(appWidgetId, sharedPreferences);

		String selectedSite = sharedPreferences.getString(PreferenceLauncherActivity.TICKER_ALERTTYPE_SITESELECTED_KEY,
				"BBC UK News");
		String feedRefreshTime = sharedPreferences.getString(PreferenceLauncherActivity.TICKER_ALERTTYPE_FEEDREFRESHTIME_KEY, "60");
		 String alertKeyword = sharedPreferences.getString(PreferenceLauncherActivity.TICKER_ALERTTYPE_KEYWORD_KEY, "*");
		boolean notificationEnabled = sharedPreferences.getBoolean(PreferenceLauncherActivity.TICKER_ALERTTYPE_NOTIFICATION_KEY, false);
		boolean soundNotification = sharedPreferences.getBoolean(PreferenceLauncherActivity.TICKER_ALERTTYPE_SOUND_KEY, false);
		boolean vibrateNotification = sharedPreferences.getBoolean(PreferenceLauncherActivity.TICKER_ALERTTYPE_VIBRATE_KEY, false);
		boolean gpsWeatherSelection = sharedPreferences.getBoolean(PreferenceLauncherActivity.TICKER_WEATHERSELECTION_GPS_CHECKBOXKEY, true);
		boolean customLocationWeatherSelectionCheckBox = sharedPreferences.getBoolean(PreferenceLauncherActivity.TICKER_WEATHERSELECTION_CUSTOMLOCATION_CHECKBOXKEY, false);
		String customLocationWeatherSelectionValue = sharedPreferences.getString(PreferenceLauncherActivity.TICKER_WEATHERSELECTION_CUSTOMLOCATION_EDITTEXTKEY, "HA98QR");
		
		
		RssFeedPreference rssFeedPreference = new RssFeedPreference();
		rssFeedPreference.setFeedRefreshTime(feedRefreshTime);
		rssFeedPreference.setNotificationEnabled(notificationEnabled);
		updateSelectedSiteInRssFeedPreference(selectedSite, rssFeedPreference);
		rssFeedPreference.setSoundNotification(soundNotification);
		rssFeedPreference.setVibrateNotification(vibrateNotification);
		rssFeedPreference.setAlertKeyword(alertKeyword);
		//weather related stuff start
		rssFeedPreference.setGpsWeatherSelection(gpsWeatherSelection);
		rssFeedPreference.setCustomLocationWeatherSelectionCheckBox(customLocationWeatherSelectionCheckBox);
		rssFeedPreference.setCustomLocationWeatherSelectionValue(customLocationWeatherSelectionValue);
		//end
		
		ApplicationStateObjectsHolder.preferenceHashMap.put(mAppWidgetId, rssFeedPreference);
	}

	private void updateSelectedSiteInRssFeedPreference(String selectedSite, RssFeedPreference rssFeedPreference) {
		String urlForSelectedSite;
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		boolean customSiteSelectionCheckBox = sharedPreferences.getBoolean(PreferenceLauncherActivity.TICKER_ALERTTYPE_SITESELECTED_CUSTOMURL_CHECKBOXKEY, false);
		if(customSiteSelectionCheckBox){
			/**User has entered custom URL.Thats the URL which needs to be used */
			urlForSelectedSite = sharedPreferences.getString(PreferenceLauncherActivity.TICKER_ALERTTYPE_SITESELECTED_CUSTOMURL_EDITTEXTKEY, "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/world/rss.xml");			
		}else{
			urlForSelectedSite = ApplicationStateObjectsHolder.displayStringToSiteUrlMap.get(selectedSite);			
		}
		rssFeedPreference.setSelectedSite(urlForSelectedSite);
	}

	private void resetCurrentFeedForWidgetInstance(int appWidgetId, SharedPreferences sharedPreferences) {
		SharedPreferences.Editor editPrefs = sharedPreferences.edit();
		editPrefs.remove(PreferenceLauncherActivity.PREF_PREFIX_KEY + appWidgetId + RssReaderService.CURRENT_FEED);
		editPrefs.commit();
	}

	private void configureAlarm() {
		Intent widgetUpdate = new Intent(this, SkyNewsReaderAppWidget.class);
		widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId });
		widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		widgetUpdate.putExtra("unique", "unique");

		// make this pending intent unique
		widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(SkyNewsReaderAppWidget.URI_SCHEME + "://widget/id/"), String.valueOf(mAppWidgetId)));
		PendingIntent newPending = PendingIntent.getBroadcast(getApplicationContext(), 0, widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);

		// schedule the new widget for updating
		AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
		int updateRateInMins = Integer.parseInt(getSharedPreferenceForFeedRefreshTime(this, mAppWidgetId));
		alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), updateRateInMins * 1000 * 60, newPending);

	}
	

	private String getSharedPreferenceForFeedRefreshTime(Context context, int appWidgetId) {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		String feedRefreshTime = sharedPreferences.getString(PreferenceLauncherActivity.PREF_PREFIX_KEY + appWidgetId
				+ R.id.widget_configuration_feedrefresheditbutton, "10");
		return feedRefreshTime;
	}
	
	

	private void setResultForActivity() {
		Intent resultValue = new Intent();
		resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		setResult(RESULT_OK, resultValue);
	}

	private void updateRemoteViewWithLoadingMessage(Context context, int appWidgetId) {
		RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_word);
		updateViews.setTextViewText(R.id.word_title, "Loading...Trying to connect to network...Please Wait.Thank You For Your Patience.");
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		manager.updateAppWidget(mAppWidgetId, updateViews);
		finish();
	}

	private static void savePreferenceAsString(Context context, String key, String text) {
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor prefs = sharedPreferences.edit();
		prefs.putString(key, text);
		prefs.commit();
	}

}
